# Copyrights Anil Osman TUR 2017
%matplotlib inline
%load_ext autoreload
from matplotlib import pyplot as plt
import cv2
import numpy as np
import imagefunctions as IF
%autoreload 2
imageGray = cv2.imread("../pics/elephant.jpg", cv2.IMREAD_GRAYSCALE)
imageColor = cv2.imread("../pics/elephant.jpg", cv2.IMREAD_COLOR)
# rgb conversiton is needed for seeing the original colors in matplotlib
# because opencv reads and conserves it in bgr form not in rgb form
b,g,r = cv2.split(imageColor)
imageColor = cv2.merge((r,g,b))
plt.subplot(1,2,1),plt.imshow(imageGray, "gray"),plt.title('Grayscale')
plt.subplot(1,2,2),plt.imshow(imageColor),plt.title('Color')
plt.show()
def flipImage(image, flag):
# lets choose 1 for vertical 0 for horizontal and 2 for both
if ( flag == 1 ):
# vertical flip
new_image = image[:,::-1]
elif ( flag == 0 ):
# horizontal flip
new_image = image[::-1,:]
elif (flag == 2 ):
# origin flip
new_image = image[::-1, ::-1]
return new_image
plt.rcParams["figure.figsize"] = 15, 60
# gray sacale
plt.subplot(1,4,1),plt.imshow(imageGray, 'gray'), plt.title('Original')
plt.subplot(1,4,2),plt.imshow(IF.flipImage(imageGray, 0), 'gray'), plt.title('Horizontal Flip')
plt.subplot(1,4,3),plt.imshow(IF.flipImage(imageGray, 1), 'gray'), plt.title('Vertical Flip')
plt.subplot(1,4,4),plt.imshow(IF.flipImage(imageGray, 2), 'gray'), plt.title('Both Flip')
plt.show()
# color
plt.subplot(1,4,1),plt.imshow(imageColor), plt.title('Original')
plt.subplot(1,4,2),plt.imshow(IF.flipImage(imageColor, 0)), plt.title('Horizontal Flip')
plt.subplot(1,4,3),plt.imshow(IF.flipImage(imageColor, 1)), plt.title('Vertical Flip')
plt.subplot(1,4,4),plt.imshow(IF.flipImage(imageColor, 2)), plt.title('Both Flip')
plt.show()
def inverseImage(image):
w = image.shape[0]
h = image.shape[1]
for i in xrange(w):
for j in range(h):
if not (len(image.shape) == 3):
image[i,j] = np.uint8(255 - image[i,j])
else:
image[i,j][0] = np.uint8(255 - image[i,j][0])
image[i,j][1] = np.uint8(255 - image[i,j][1])
image[i,j][2] = np.uint8(255 - image[i,j][2])
return image
plt.rcParams["figure.figsize"] = 10, 20
# gray sacale
plt.subplot(1,2,1),plt.imshow(imageGray, 'gray'), plt.title('Original')
plt.subplot(1,2,2),plt.imshow(IF.inverseImage(imageGray.copy()), 'gray'), plt.title('Inverse')
plt.show()
# color
plt.subplot(1,2,1),plt.imshow(imageColor), plt.title('Original')
plt.subplot(1,2,2),plt.imshow(IF.inverseImage(imageColor.copy())), plt.title('Inverse')
plt.show()
def avgIntensity(image):
w = image.shape[0]
h = image.shape[1]
if len(image.shape) == 3: # it is colored
b,g,r = cv2.split(image)
ciAvg = np.array([np.sum(b),np.sum(g),np.sum(r)]) / (w*h) # color intesity average
print ("average intensities: ", ciAvg)
return ciAvg
else:
iAvg = int( np.sum(image) / (w*h) )
print ("average intensity: ", iAvg)
return iAvg
return -1 # if haven't returned yet there is a problem
print (IF.avgIntensity(imageGray))
print (IF.avgIntensity(imageColor))
def thresholdImg(image, threshold):
if len(image.shape) == 3: # it is colored
colors = cv2.split(image)
if not isinstance(threshold, int):
if len(threshold) == 3:
for i in xrange(3):
colors[i] = np.uint8(255) * (colors[i] > threshold[i])
else:
print ("3 parameter needed to apply treshold with different values")
else:
for i in xrange(3):
colors[i] = np.uint8(255) * (colors[i] > threshold)
return cv2.merge(colors)
else:
return 255 * ( image > threshold )
return -1 # if haven't returned yet there is a problem
threshold = 200
plt.rcParams["figure.figsize"] = 10, 30
# gray sacale
plt.subplot(1,2,1),plt.imshow(imageGray, 'gray'), plt.title('Original')
plt.subplot(1,2,2),plt.imshow(IF.thresholdImg(imageGray, threshold), 'gray'), plt.title('Tresholded')
plt.show()
threshold = [130, 150, 170]
# color
plt.subplot(1,2,1),plt.imshow(imageColor), plt.title('Original')
plt.subplot(1,2,2),plt.imshow(IF.thresholdImg(imageColor, threshold)), plt.title('Tresholded')
plt.show()
plt.rcParams["figure.figsize"] = 10, 20
# gray sacale
plt.subplot(1,2,1),plt.imshow(imageGray, 'gray'), plt.title('Original')
plt.subplot(1,2,2),plt.imshow(IF.tresholdWithAvg(imageGray), 'gray'), plt.title('Tresholded')
plt.show()
# color
plt.subplot(1,2,1),plt.imshow(imageColor), plt.title('Original')
plt.subplot(1,2,2),plt.imshow(IF.tresholdWithAvg(imageColor)), plt.title('Tresholded')
plt.show()
# for seeing better result another picture
imageGray = cv2.imread("../pics/elephant2.jpg", cv2.IMREAD_GRAYSCALE)
imageColor = cv2.imread("../pics/elephant2.jpg", cv2.IMREAD_COLOR)
# rgb conversiton is needed for seeing the original colors in matplotlib
# because opencv reads and conserves it in bgr form not in rgb form
b,g,r = cv2.split(imageColor)
imageColor = cv2.merge((r,g,b))
plt.subplot(1,2,1),plt.imshow(imageGray, "gray"),plt.title('Grayscale')
plt.subplot(1,2,2),plt.imshow(imageColor),plt.title('Color')
plt.show()
# histogram helper function to draw
def plotHistogram(histData):
plt.close('all')
plt.rcParams["figure.figsize"] = [20, 3]
width = 3
x = np.arange(256)
if len(histData) == 3:
plt.bar(x, histData[0], width/3, color='b')
plt.bar(x, histData[1], width/3, color='g')
plt.bar(x, histData[2], width/3, color='r')
plt.show()
else:
plt.bar(x, histData, width/3, color='b')
plt.show()
def plotHistogramSeprate(histData):
plt.close('all')
plt.rcParams["figure.figsize"] = [20,10]
width = 3
x = np.arange(256)
if len(histData) == 3:
plt.close('all')
plt.subplot(3, 1, 1), plt.bar(x, histog[0], width/3, color='b')
plt.subplot(3, 1, 2), plt.bar(x, histog[1], width/3, color='g')
plt.subplot(3, 1, 3), plt.bar(x, histog[2], width/3, color='r')
plt.show()
else:
plt.bar(x, histData, width/3, color='b')
plt.show()
histog = IF.generateHistogram(imageGray)
print (histog)
plotHistogram(histog)
histog = IF.generateHistogram(imageColor)
plotHistogram(histog)
plotHistogramSeprate(histog)
def equalizeHistogram(image):
cols = image.shape[0]
rows = image.shape[1]
hist = IF.generateHistogram(image)
if (len(image.shape) == 2 ):
sample = cols * rows
histFunc = hist / float(sample)
plt.plot(histFunc)
plt.show()
for i in range(1,hist.size):
histFunc[i] = histFunc[i-1] + histFunc[i]
plt.plot(histFunc)
plt.show()
new_image = np.zeros(image.shape, dtype=np.uint8)
for i in range(cols):
for j in range(rows):
new_image[i,j] = np.uint8( round(histFunc[image[i,j]] * image[i,j]) )
return new_image
def generateHistogram(image):
cols = image.shape[0]
rows = image.shape[1]
if (len(image.shape) == 2 ):
histData = np.zeros(256) # as a range 0 - 255 used
flatImage = image.flatten()
for i in range(len(flatImage)):
histData[flatImage[i]] += 1
#for i in xrange(cols):
# for j in xrange(rows):
# histData[image[i,j]] += 1
return histData
elif (len(image.shape) == 3):
b,g,r = cv2.split(image)
histData = [generateHistogram(b),generateHistogram(g),generateHistogram(r)]
return histData
return -1 # if haven't returned yet there is a problem
equalizeHistogram(imageGray)
h = histog[0]
print (imageGray.shape)
x = np.arange(256)
plt.plot(x,h)
plt.show()
n_imageGray = equalizeHistogram(imageGray)
plt.rcParams["figure.figsize"] = [10, 8]
plt.subplot(121),plt.imshow(n_imageGray, cmap='gray'),plt.title('Histogram Equalized')
plt.subplot(122),plt.imshow(imageGray, cmap='gray'),plt.title('ORIGINAL')
plt.show()
histog = IF.generateHistogram(n_imageGray)
print (histog)
plotHistogram(histog)
x = np.arange(256)
plt.plot(x,histog)
plt.show()
histog = IF.generateHistogram(imageGray)
plotHistogram(histog)
x = np.arange(256)
plt.plot(x,histog)
plt.show()
n_imageColor = IF.equalizeHistogram(imageColor)
plt.rcParams["figure.figsize"] = [10, 8]
plt.subplot(121),plt.imshow(n_imageColor),plt.title('Histogram Equalized')
plt.subplot(122),plt.imshow(imageColor),plt.title('ORIGINAL')
plt.show()
histog = IF.generateHistogram(n_imageColor)
plotHistogramSeprate(histog)
histog = IF.generateHistogram(imageColor)
plotHistogramSeprate(histog)